import { App } from 'vue'

const allComponent = require.context('.', true, /Index\.vue$/)
const allComponentConfig = require.context('.', true, /config\.json$/)

// 注册全局组件
export default {
  install(app: App) {
    allComponent.keys().forEach((path) => {
      const name = path.split('/')[1]
      app.component(name, allComponent(path).default)
    })
  }
}

// 左侧组件库数据
let widgetList: Record<string, any> = {}
allComponentConfig.keys().forEach((path) => {
  const config = allComponentConfig(path)
  const { id, name, icon, componentName, sort, fields = [] } = config

  let widgetConfig: Record<string, any> = {
    id,
    name,
    icon,
    componentName,
    sort
  }
  fields.map((field: Record<string, any>) => {
    field.list.forEach((item: Record<string, any>) => {
      if (!widgetConfig[field.key]) widgetConfig[field.key] = {}
      widgetConfig[field.key][item.key] = item.defaultValue
    })
  })
  if (widgetList[config.type]) {
    widgetList[config.type].list.push(widgetConfig)
  } else {
    widgetList[config.type] = { title: config.typeText, list: [widgetConfig] }
  }
})

export const widgetListConfig = [
  {
    ...widgetList.base,
    key: 'base',
    list: widgetList.base.list.sort(
      (a: Record<string, any>, b: Record<string, any>) => a.sort - b.sort
    )
  }
  // { title: '业务组件', key: 'business', list: [] }
]

// 右侧属性设置数据
let componentAttributeList: Record<string, object> = {}
allComponentConfig.keys().forEach((path) => {
  const config = allComponentConfig(path)
  componentAttributeList[config.componentName] = config.fields
})
export const getComponentAttribute = (name: string) =>
  componentAttributeList[name]
